<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
namespace ApplicationsModule\GalleryModule;

use Nette\Object;
use \SimpleXMLElement;

use ApplicationsModule\GalleryModule\PicasaTokenNotValidException;

/**
 * Description of PicasaWebLite
 *
 * @author honza
 */
class PicasaWebLite extends Object {
    
    const DEFAULT_FEED_URL = "https://picasaweb.google.com/data/feed/api/";
    const DEFAULT_URL = "https://picasaweb.google.com/data/feed/api/user/default/";
    const DEFAULT_ENTRY_URL = "https://picasaweb.google.com/data/entry/api/";
    const XMLNS_GPHOTO = 'http://schemas.google.com/photos/2007';
    const XMLNS_MEDIA = 'http://search.yahoo.com/mrss/';
    
    private function load($url, $token) {
        $urlToken = $this->appendToken($url, $token);
        $ch = curl_init($urlToken);
        
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        $response = curl_exec($ch);
        $info = curl_getinfo($ch);
        
        //TODO: docasne
        if($info["http_code"] == 403) {
            throw new PicasaTokenNotValidException("Token is not valid", 403);
        }
        curl_close($ch);
        //$children = $xml->children("http://schemas.google.com/photos/2007");
        //return $children;
        return $response;
    }
    
    public function createAlbum($name, $token) {
        $url = self::DEFAULT_FEED_URL . "user" . "/default";
        $urlToken = $this->appendToken($url, $token);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $urlToken);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/atom+xml"));
        $timestamp = time();
        $data = "<entry xmlns='http://www.w3.org/2005/Atom'
    xmlns:media='http://search.yahoo.com/mrss/'
    xmlns:gphoto='http://schemas.google.com/photos/2007'>
  <title type='text'>$name</title>
  <summary type='text'>This was the recent trip I took to Italy.</summary>
  <gphoto:access>private</gphoto:access>
  <gphoto:timestamp>$timestamp</gphoto:timestamp>
  <media:group>
    <media:keywords></media:keywords>
  </media:group>
  <category scheme='http://schemas.google.com/g/2005#kind'
    term='http://schemas.google.com/photos/2007#album'></category>
</entry>
";
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
    }
    
    private function delete($url, $token, $headers = null) {
        $url = $this->appendToken($url, $token);
        
        if($headers == null) {
            $headers = array("If-Match: *");
        }
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);
        $info = curl_getinfo($ch);
    }
    
    public function deleteAlbum($albumID, $token, $force) {
        $url = self::DEFAULT_ENTRY_URL . "user/default/albumid/" . $albumID;
        $this->delete($url, $token);
    }
    
    public function loadAlbumSamples($token, $blankAlbums = false, $fields = array()) {
        $url = self::DEFAULT_URL;
        $albums = $this->loadAlbums($url, $token, $blankAlbums);
        return $albums;
    }
    
    public function loadAlbums($url, $token, $blankAlbums) {
        $response = $this->load($url, $token);
        $xml = $this->makeXML($response);
        \Nette\Debug::$maxDepth = 30;
        \Nette\Debug::$maxLen = 500;
        $albums = array();
        foreach($xml->entry as $entry) {
            $album = $this->setAlbumAttributes($entry);
            if(($album->getNumOfPhotos() > 0) || $blankAlbums) {
                $albums[] = $album;
            }
        }
        //$children = $xml->children(self::XMLNS_GPHOTO);
        return $albums;
    }
    
    public function loadPhotosFromAlbum($userID, $albumID, $token) {
        $url = $this->makeUrlForAlbum($userID, $albumID);
        $data = $this->load($url, $token);
        $xml = $this->makeXML($data);
        $photos = array();
        foreach($xml->entry as $entry) {
            $photos[] = $this->setPhotoAttributes($entry);
        }
        return $photos;
    }
    
    public function savePhotos($token, $params) {
        $url = self::DEFAULT_FEED_URL . "user/default" . "/albumid/" . $params["albumID"];
        $url = $this->appendToken($url, $token);
        
        $headers = array("Content-Type: " . $params["mimetype"], "Content-Length: " . strlen($params["data"]), "Slug: " . $params["photoName"]);
        /*$xmlEntry = "<entry xmlns='http://www.w3.org/2005/Atom'>
  <title>{$params["photoName"]}</title>
  <summary>Real cat wants attention too.</summary>
  <category scheme='http://schemas.google.com/g/2005#kind'
    term='http://schemas.google.com/photos/2007#photo'/>
</entry>";*/
    //$fields = array($xmlEntry, $params["data"]);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params["data"]);
        
        $response = curl_exec($ch);
        $info = curl_getinfo($ch); //Vraci 400 kdyz se posere nahravani        
        
    }
    
    private function appendToken($url, $token) {
        $url = $url . "?oauth_token=" . $token;
        return $url;
    }
    
    private function makeXML($data) {
        $xml = new SimpleXMLElement($data);
        return $xml;
    }
    
    private function setAlbumAttributes($entry) {
        $album = new PicasaAlbum();
        
        $album->setTitle($entry->title->__toString());
        $album->setService("picasa");
        $entryItemPhoto = $entry->children(self::XMLNS_GPHOTO);
        $album->setId($entryItemPhoto->id->__toString());
        $album->setName($entryItemPhoto->name->__toString());
        $album->setTimestamp($entryItemPhoto->timestamp->__toString());
        $album->setNumOfPhotos($entryItemPhoto->numphotos->__toString());
        $album->setIdUser($entryItemPhoto->user->__toString());
        $album->setCommentingEnabled($entryItemPhoto->commentingEnabled->__toString());
        $album->setCommentCount($entryItemPhoto->commentCount->__toString());
        
        
        $entryItemMedia = $entry->children(self::XMLNS_MEDIA);        
        $content = $entryItemMedia->xpath('media:content');
        $album->setContentUrl($this->getAttribute("url", $content, 0));
        
        $description = $entryItemMedia->xpath('media:description');
        $album->setDescription($description[0]->__toString());
        $thumbnail = $entryItemMedia->xpath('media:thumbnail');
        $album->setThumbnail($this->getAttribute("url", $thumbnail, 0));
        
        return $album;
    }
    
    private function setPhotoAttributes($entry) {
        $photo = new PicasaPhoto();
        $photo->setTitle($entry->title->__toString());
        $photo->setService("picasa");
        
        $entryItemPhoto = $entry->children(self::XMLNS_GPHOTO);
        $photo->setId($entryItemPhoto->id->__toString());
        $photo->setName($photo->getTitle());
        $photo->setTimestamp($entryItemPhoto->timestamp->__toString());
        $photo->setCommentingEnabled($entryItemPhoto->commentingEnabled->__toString());
        $photo->setCommentCount($entryItemPhoto->commentCount->__toString());
        
        $entryItemMedia = $entry->children(self::XMLNS_MEDIA);
        
        $entryItemMedia = $entry->children(self::XMLNS_MEDIA);        
        $content = $entryItemMedia->xpath('media:content');
        $photo->setContentUrl($this->getAttribute("url", $content, 0));
        
        $description = $entryItemMedia->xpath('media:description');
        $photo->setDescription($description[0]->__toString());
        $thumbnail = $entryItemMedia->xpath('media:thumbnail');
        $photo->setThumbnail($this->getAttribute("url", $thumbnail, 2));
        
        return $photo;
    }
    
    private function getAttribute($attr, $xpath, $index) {
        $attributes = $xpath[$index]->attributes();
        return $attributes[$attr]->__toString();
    }
    
    private function makeUrlForAlbum($userID, $albumID) {
        return self::DEFAULT_FEED_URL . 
                "user/" . $userID . 
                "/albumid/" . $albumID;
    }
    
    private function setFields($url, array $fields) {
        if(empty($fields)) {
            return $url;
        }
        $fieldsImploded = implode(",", $fields);
        $url = $url . "&fields=(" . $fieldsImploded . ")";
        
        return $url;
    }
    
    public function getUserForPicasa($token) {
        $url = self::DEFAULT_URL;
        $response = $this->load($url, $token);
        $xml = new \SimpleXMLIterator($response);
        $id = $xml->title->__toString();
        return $id;
    }
}

?>
